package com.yifeng.repo.endpoint.security.context.filter;

import com.yifeng.repo.endpoint.security.auth.SecurityCheckerFactory;
import com.yifeng.repo.endpoint.security.console.api.dto.AccountDto;
import com.yifeng.repo.endpoint.security.console.api.dto.AccountPermissionDto;
import com.yifeng.repo.endpoint.security.context.manager.RequestContextManager;
import com.yifeng.repo.endpoint.security.redis.worker.RedisCacheWorker;

import javax.servlet.*;
import java.io.IOException;

/**
 * Created by daibing on 2023/8/22.
 */
public class AppSecurityFilter implements Filter {
    /**
     * BUSINESS、CUSTOMER、SUPPLY
     */
    private final String consoleType;
    private final boolean loadPermission;

    public AppSecurityFilter(String consoleType, String url, String accessToken, int clientTimeoutMillis,
                             boolean loadPermission, RedisCacheWorker redisCacheWorker, String redisKeyPrefix) {
        this.consoleType = consoleType;
        this.loadPermission = loadPermission;
        SecurityCheckerFactory.get(consoleType).init(url, accessToken, clientTimeoutMillis, redisCacheWorker, redisKeyPrefix);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 检查 token
        String token = SecurityCheckerFactory.get(consoleType).checkToken(request);

        // 检查 account
        AccountDto accountDto = SecurityCheckerFactory.get(consoleType).checkAccount(request, token);
        if (accountDto != null) {
            RequestContextManager.setAccount(accountDto);
        }

        // 检查 permission
        if (!loadPermission || accountDto == null) {
            return;
        }
        AccountPermissionDto accountPermissionDto = SecurityCheckerFactory.get(consoleType).checkPermission(accountDto.getCode());
        RequestContextManager.setPermission(accountPermissionDto);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
